package com.wxxymaker.model.dao;

import com.blade.ioc.annotation.Bean;
import com.wxxymaker.model.entity.Visitor;
import com.wxxymaker.utils.Const;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.core.AnimaQuery;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;

import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2018/8/16 17:28
 * @DESCRIBE
 */
@Bean
public class VisitorDao implements BaseDao<Visitor> {
    @Override
    public Visitor add(Visitor entity) {
        if (entity != null) {
            Integer asInt = entity.save().asInt();
            entity.setId(asInt);
        }
        return entity;
    }

    @Override
    public Visitor delete(int id) {
        if (id > 0) {
            Visitor visitor = Anima.select().from(Visitor.class).byId(id);
            if (visitor != null) {
                if (visitor.delete() > 0) {
                    return visitor;
                }
            }
        }
        return null;
    }

    @Override
    public int change(Visitor entity) {
        if (entity != null && entity.getId() > 0) {
            return entity.updateById(entity.getId());
        }
        return 0;
    }

    @Override
    public Visitor findOne(int id) {
        return Anima.select().from(Visitor.class).byId(id);
    }

    public Page<Visitor> page(int pageNo) {
        return page(pageNo, Const.shortPageSize, null);
    }

    public Page<Visitor> page(int pageNo, String time) {
        return page(pageNo, Const.shortPageSize, time);
    }

    public Page<Visitor> page(int pageNo, int size, String time) {
        AnimaQuery<Visitor> from = Anima.select().from(Visitor.class)
                .order(Visitor::getTime, OrderBy.DESC);
        if (time != null) {
            from.like(Visitor::getTime, "%" + time + "%");
        }
        return from.page(pageNo, size);
    }

    public long count(String time) {
        AnimaQuery<Visitor> from = Anima.select().from(Visitor.class);
        if (time != null) {
            from.like(Visitor::getTime, "%" + time + "%");
        }
        return from.count();
    }

    @SuppressWarnings("unchecked")
    public List<String> times() {
        return new AnimaQuery().queryList(String.class,
                "SELECT SUBSTR(time,1,11) FROM visitor " +
                        "GROUP BY SUBSTR(time,1,11)" +
                        " ORDER BY time DESC", (Object[]) null);
    }
}
